<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] - ".($_GET["type"]=="add"? "Add" : "Update")." Product";
$page_title=($_GET["type"]=="add"? "Add" : "Update")." Product";
$prod_list_file=$vars["file"]["admin"]["product_list"];

if(!$pv["task"]["Products"] || !$pv["task"]["Add/Update Products"]){
	$errmsg="<h2>$page_title</h2>".format_err("You do not have the privilege to manage product.");

	print format_admin_page($errmsg, $this_title);
	exit();
}

if(!in_array($_GET["type"], array("add","edit"))){
	header("location: $this_file?type=add");
	exit();
}

if($_GET["type"]=="edit"){
	if(!$get_s["id"]){
		$errmsg="No product with that ID found!";
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->products where id='$get_d[id]'"))){
		$errmsg="No product with that ID found!";
	}else{
		$r_prod=mysql_fetch_assoc($r);
		$linked_cat = @mysql_fetch_assoc(mysql_query("select * from $db->product_category where id='$r_prod[catid]'"));
	}
}

if(!@mysql_num_rows(mysql_query("select * from $db->product_category"))){
	$errmsg=__("No product category found, please setup the product category first.");
}

if($errmsg){
	$errmsg="<h2>$page_title</h2>".format_err($errmsg);

	print format_admin_page($errmsg, $this_title);
	exit();
}

$r_cat[0]="";
$r_cat_d[""]=__("Please select a category");
$r_scat[0]="";
$r_scat_d[""]=__("All categories");
$cats=get_all_subcat_by_maincat();
for($i=0,$t=count($cats);$i<$t;$i++){
	$r_cat[($i+1)]=$cats[$i]["id"];
	$r_cat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
	$r_scat[($i+1)]=$cats[$i]["id"];
	$r_scat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
}
$r_prodtype=array("n","p");
$r_prodtype_d=array("n"=>__("Normal"),"p"=>__("Package"));
$r_status=array("active","inactive");
$r_status_delete=array("active","inactive","deleted");
$r_status_d=array("active"=>__("Active"),"inactive"=>__("Inactive"),"deleted"=>__("Deleted"));
$r_qty_trans = array('c','d');
$r_qty_trans_d = array('c'=>__("Add"),'d'=>__("Deduct"));

$td_width=180;
$datetime=ndate($vars["system_date_format"]);

require_once(M_ROOT."/classes/cls_search_cat_display.php");

//#####AJAX CALL#####
//search product
if($_GET["aj"] && $_GET["search_prod"]){
	$o_searchcat = new SearchCat($post_d['catid'], $product_title = $post_d['title'], $cur_page = 0, $item_per_page = 10);
	print $o_searchcat->display();
	exit();
}
//#####END AJAX CALL#####

//#####ADD / EDIT PRODUCT POST#####
if($_POST["__req"]){
	//#####ERROR CHECK#####
	$chk_arr="_title,_descr,_remark";
	if($_GET["type"]=="add"){
		$chk_arr.=",_refno";
	}
	if($post_s["prod_type"]=="n" && $post_s["qty_type"] == "l" && ($get_s['type'] == 'add' || ($get_s['type'] == 'edit' && strlen($post_s['_qty'])))){
		$chk_arr.=",_qty";
	}
	if($post_s["prod_type"]=="n"){
		$chk_err.=",_bv";
	}
	if($post_s["prod_type"]=="p"){
		$fixed_check=array("bv","dp","rp");
		foreach($fixed_check as $field){
			if($post_s[$field."_fix"]){
				$chk_arr.=",_total_".$field;
			}
		}
	}
	$chk_arr=explode(",", $chk_arr);
	foreach($post_s as $f=>$v){
		if(in_array($f, $chk_arr)){
			$data[$f]=$v;
		}
	}
	$errmsg=verify_form_data("products", $data);

	if(!$errmsg){
		if(!strlen($post_s["catid"]) || !in_array($post_s["catid"], $r_cat)){
			$errmsg.=__("Please select a category.")."<br />\n";
		}
		if($_GET["type"]=="add" && prod_refno_found($post_d["_refno"])){
			$errmsg.=replace_tag(__("The Reference No. '<%refno%>' is already used by another product."), array("<%refno%>"=>$post_h["_refno"]))."<br />\n";
		}
		//check package product entry
		if($post_s["prod_type"]=="p"){
			$i=0;
			foreach($post_d as $f=>$v){
				if(preg_match('/^e_refno_/', $f)){
					$pi=preg_replace('/e_refno_/', '', $f);
					$prods[$i]["refno"]=$v;
					$prods[$i]["qty"]=$post_d["e_qty_$pi"];
					$prodss[$i]['refno']=stripslashes($v);//for display
					$i++;
				}
			}
			if(!count($prods)){
				$errmsg.=__("You must provide at least one product for a package.")."<br />\n";
			}else{
				$prod_dbr=explode("#", $vars["dbr"]["package_detail"]["qty"]);
				$all_prods=array();
				for($i=0,$t=count($prods);$i<$t;$i++){
					//cannot link to self
					if($_GET["type"]=="edit" && $prods[$i]["refno"] == $r_prod["refno"]){
						$errmsg.=replace_tag(__("The package cannot link back to itself (reference no. '<%refno%>')."), array("<%refno%>"=>$prodss[$i]["refno"]))."<br />\n";
					}
					//check for duplicate
					if(in_array($prods[$i]["refno"], $all_prods)){
						$errmsg.=replace_tag(__("Some of the same product (reference no. '<%refno%>') has been entered more than once."), array("<%refno%>"=>$prodss[$i]["refno"]))."<br />\n";
						$i=$t;
						//check refno / qty / if product itself is a package & the products linked is the same country
					}else{
						$all_prods[]=$prods[$i]["refno"];
						$this_prod=@mysql_fetch_assoc(mysql_query("select id, catid, prod_type from $db->products where refno='".$prods[$i]["refno"]."'")) or false;
						if(!$this_prod){
							$errmsg.=replace_tag(__("Product with reference no. '<%ref%>' could not be found."), array("<%ref%>"=>$prodss[$i]["refno"]))."<br />\n";
						}elseif($this_prod["prod_type"]=="p"){
							$errmsg.=replace_tag(__("Product with reference no. '<%ref%>' is a package. You cannot link a package."), array("<%ref%>"=>$prodss[$i]["refno"]))."<br />\n";
						}else{
							$prods[$i]["id"]=$this_prod["id"];
						}
						if(!strlen($prods[$i]["qty"])){
							$errmsg.=replace_tag(__("Please provide a quantity for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prodss[$i]["refno"]))."<br />\n";
						}elseif(!is_numeric($prods[$i]["qty"]) || $prods[$i]["qty"]<=0){
							$errmsg.=replace_tag(__("Please provide a valid quantity (numerical with value more than zero) for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prodss[$i]["refno"]))."<br />\n";
						}elseif($prods[$i]["qty"] > $prod_dbr[6]){
							$errmsg.=replace_tag(__("Please provide a quantity in the range <%from%> to <%to%> for the product with reference no. '<%ref%>', you have provided <%x%>."), array("<%ref%>"=>$prodss[$i]["refno"], "<%from%>"=>"1", "<%to%>"=>strval($prod_dbr[6]), "<%x%>"=>$prods[$i]["qty"]))."<br />\n";
						}
					}
				}
			}
		}

		//not allow to change product type
		if($_GET["type"]=="edit" && $r_prod["prod_type"] != $post_s["prod_type"]){
			$errmsg.=__("You are not allowed to change the product type.")."<br />";
		}
		//check quantity
		if($get_s['type'] == 'edit' && $post_s['qty_type'] == 'l' && $post_s['qty_trans'] == 'd'){
			if($r_prod['qty'] < $post_s['_qty']){
				$errmsg.=__("This product does not have sufficient quantity for this quantity deduction.")."<br />";
			}
		}
		//check status
		if(!in_array($post_s["status"], $r_status)){
			$errmsg.=__("You have selected an invalid status.")."<br />\n";
		}
		//check uploaded image
		if(!empty($_FILES["prod_image"]["name"])){
			$prod_image_uploaded = true;
			$prod_image=$_FILES["prod_image"];
			$prod_image["extension"]=substr($prod_image["name"], strrpos($prod_image["name"], ".")+1);
			$prod_image["formatted_name"]=substr(preg_replace('/[^a-zA-Z0-9]+/', '', substr($prod_image["name"], 0, strrpos($prod_image["name"], "."))), 0, 20)."_".ntime().".".$prod_image["extension"];
			if($prod_image["error"]){
				$errmsg.=__("There was some error uploading the product image.")."<br />\n";
			}elseif(!in_array(strtolower($prod_image["extension"]), $vars["accepted_image_format"])){
				$errmsg.=replace_tag(__("The uploaded product image is not accepted. Only file of type <%type%> is accepted."), array("<%type%>"=>implode(" / ", $vars["accepted_image_format"])))."<br />\n";
			}elseif($prod_image["size"] > $vars["prod_image_max_size"]*1024){
				$errmsg.=replace_tag(__("The uploaded product image is too large, maximum upload size is <%x%> <%unit%>."), array("<%x%>"=>strval($vars["prod_image_max_size"]), "<%unit%>"=>__("KB")))."<br />\n";
			}
		}
	}
	//#####END ERROR CHECK#####

	//#####ADD TO DB#####
	if(!$errmsg){
		$qty=$post_s["prod_type"]=="p"? 0 : $post_s["qty_type"] == "u"? 0 : $post_d["_qty"];
		$fixed_db=array("_bv","_dp","_rp");
		foreach($fixed_db as $field){
			$ffield=substr($field, 1);
			$db_fix[$ffield]=$post_s["prod_type"]=="p"? ($post_s[$ffield."_fix"]? "y" : "n") : "";
			$db_fixpoint[$ffield]=$post_s["prod_type"]=="p"? ($post_s[$ffield."_fix"]? $post_d["_total_".$ffield] : 0) : $post_d[$field];
			$db_fix_add_fq.=", ".$ffield."_fix, $ffield";
			$db_fix_add_vq.=", '".$db_fix[$ffield]."', '".$db_fixpoint[$ffield]."'";
			$db_fix_edit_uvq.=", ".$ffield."_fix='".$db_fix[$ffield]."', $ffield='".$db_fixpoint[$ffield]."'";
		}
		if($_GET["type"]=="add"){//add
			if($prod_image_uploaded){
				$image_file=$prod_image["formatted_name"];
			}
			$sql="insert into $db->products (catid, prod_type, refno, title $db_fix_add_fq, qty_type, qty, image_file, status, remark, descr, cdate)
			values ('$post_d[catid]', '$post_d[prod_type]', '$post_d[_refno]', '$post_d[_title]' $db_fix_add_vq, '$post_d[qty_type]', '$qty', '$image_file', '$post_d[status]', '$post_d[_remark]', '$post_d[_descr]', '$datetime')";
			if(!mysql_query($sql)){
				$errmsg.=__("Error creating a new product.")."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				$critical_error.="Error creating a new product.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_pid=mysql_insert_id();

				//insert qty record
				if($post_s['prod_type']=='n' && $qty > 0){
					if(!mysql_query($sql="insert into $db->prod_qty_record (pid, ttype, type, qty, cdate)
					values ('$new_pid', 'a', 'c', '$qty', '".ndate()."')")){
						$qty_errmsg.="SQL: $sql<br /><br />Error: ".mysql_error()."<br />";
						$qty_errlog.="SQL: $sql\n\nError: ".mysql_error()."\n";
					}
				}
				
				//insert package product details
				if($post_s["prod_type"]=="p"){
					for($i=0,$t=count($prods);$i<$t;$i++){
						if(!mysql_query($sql="insert into $db->package_detail (pkid, pid, refno, qty) values ('$new_pid', '".$prods[$i]["id"]."', '".$prods[$i]["refno"]."', '".$prods[$i]["qty"]."')")){
							$jsd_errmsg.="<br />\n".__("Reference No.").__(":")." ".$prods[$i]["refno"]." ".__("Quantity").__(":")." ".$prods[$i]["qty"]."<br />\n<br />\n".__("SQL:")." $sql<br />\n".__("Error:")." ".mysql_error()."<br />\n";
							$jsd_errlog.="\nReference No.: ".$prods[$i]["refno"]." Quantity: ".$prods[$i]["qty"]."\n\nSQL: $sql\nError: ".mysql_error()."\n";
						}
					}
				}

				//image upload
				if($prod_image_uploaded){
					$this_prod_root=PROD_ROOT."/".$new_pid;
					//create image directory
					if(!create_folder_if_not_exist($this_prod_root)){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/orig")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/orig"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/big")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/big"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/medium")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/medium"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/thumb")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/thumb"))."<br />\n";
					}

					//move & resize image
					if(!$f_errmsg){
						$orig_image=$this_prod_root."/orig/".$prod_image["formatted_name"];
						if(!@move_uploaded_file($prod_image["tmp_name"], $orig_image)){
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/orig/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/big/".$prod_image["formatted_name"], $vars["prod_image_dimension_big"], $vars["prod_image_dimension_big"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/big/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/medium/".$prod_image["formatted_name"], $vars["prod_image_dimension_medium"], $vars["prod_image_dimension_medium"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/medium/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/thumb/".$prod_image["formatted_name"], $vars["prod_image_dimension_thumb"], $vars["prod_image_dimension_thumb"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/thumb/"))."<br />\n";
						}
					}
				}
				$msg=__("The new product has been successfully created.")."<br />\n";
				$logstr="The new product has been successfully created.";
				$excluded_fields = array('id','cdate');
				$log_arr = mysql_fetch_assoc(mysql_query("select * from $db->products where id='$new_pid'"));
				if($log_arr){
					foreach($log_arr as $f => $v){
						if(!in_array($f, $excluded_fields)){
							$dbr = explode('#', $vars['dbr']['products'][$f]);
							$log_fields .= $dbr[4]." = ".$v."\n";
						}
					}
					$log_fields = rtrim($log_fields, "\n");
				}
				$logstr .= "\n".$log_fields;
				if($qty_errmsg || $f_errmsg || $jsd_errmsg){
					$msg.="<br />\n<span class='red'>".__("However, some error(s) had occurred:")."<br />\n<br />\n".
					($qty_errmsg? __("Quantity for some of the product(s) below could not be properly recorded:")."<br />\n$qty_errmsg<br />\n" : "").
					($jsd_errmsg? __("some of the product(s) below could not be properly linked with this package:")."<br />\n$jsd_errmsg<br />\n" : "").
					($f_errmsg? __("There is some error with the product image upload:")."<br />\n$f_errmsg" : "")."</span>";
					$critical_error=$msg;
				}
				if($qty_errlog || $jsd_errlog){
					$critical_error.=$logstr."\nHowever, some error(s) had occurred:\n\n".
					($qty_errlog? "Quantity for some of the product(s) below could not be properly recorded:\n$qty_errlog\n" : "").
					($jsd_errlog? "some of the product(s) below could not be properly linked with this package:\n$jsd_errmsg\n" : "");
					$logstr = '';
				}
			}
		}else{//update
			if($prod_image_uploaded){
				$image_file_q=", image_file='$prod_image[formatted_name]'";
			}elseif($post_s["delete_prod_image"]){
				$image_file_q=", image_file=''";
			}
			$qty_q = '';
			if($r_prod['prod_type'] == 'n'){
				if($post_s['qty_type'] == 'l'){
					if($qty > 0){
						if($post_s['qty_trans'] == 'c'){
							$qty_q = ", qty=qty+$qty";
						}else{
							$qty_q = ", qty=qty-$qty";
						}
					}
				}elseif($r_prod['qty_type'] == 'l'){//update from limited to unlimited
					//$qty_q = ", qty=$qty";
				}
			}
			$sql="update $db->products set catid='$post_d[catid]', title='$post_d[_title]', qty_type='$post_d[qty_type]'  $db_fix_edit_uvq $qty_q $image_file_q, status='$post_d[status]', remark='$post_d[_remark]', descr='$post_d[_descr]' where id='$get_d[id]' limit 1";
			if(!mysql_query($sql)){
				$errmsg.=__("Error updating the product record.")."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				$critical_error.="Error updating the product record.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}
			if(!$errmsg){
				//insert qty record
				if($r_prod['prod_type']=='n' && $qty > 0){
					if(!mysql_query($sql="insert into $db->prod_qty_record (pid, ttype, type, qty, cdate)
					values ('$get_d[id]', 'a', '$post_d[qty_trans]', '$qty', '".ndate()."')")){
						$qty_errmsg.="SQL: $sql<br /><br />Error: ".mysql_error()."<br />";
						$qty_errlog.="SQL: $sql\n\nError: ".mysql_error()."\n";
					}
				}
				
				if($r_prod["prod_type"]=="p"){
					//insert / update package product
					for($i=0,$t=count($prods);$i<$t;$i++){
						if(@mysql_num_rows(mysql_query("select id from $db->package_detail where pkid='$get_d[id]' and pid='".$prods[$i]["id"]."'"))){
							$sql="update $db->package_detail set qty='".$prods[$i]["qty"]."', refno='".$prods[$i]["refno"]."' where pkid='$get_d[id]' and pid='".$prods[$i]["id"]."'";
						}else{
							$sql="insert into $db->package_detail (pkid, pid, refno, qty) values ('$get_d[id]', '".$prods[$i]["id"]."', '".$prods[$i]["refno"]."', '".$prods[$i]["qty"]."')";
						}
						if(!mysql_query($sql)){
							$jsd_errmsg.="<br />\n".__("Reference No.").__(":")." ".$prods[$i]["refno"]." ".__("Quantity").__(":")." ".$prods[$i]["qty"]."<br />\n<br />\n".__("SQL:")." $sql<br />\n".__("Error:")." ".mysql_error()."<br />\n";
							$jsd_errlog.="\nReference No.: ".$prods[$i]["refno"]." Quantity: ".$prods[$i]["qty"]."\n\nSQL: $sql\nError: ".mysql_error()."\n";
						}
						$inserted_pid.=($inserted_pid? "," : "")."'".$prods[$i]["id"]."'";
					}
					//delete unlinked products
					if($t=@mysql_num_rows($rd=mysql_query("select pid from $db->package_detail where pkid='$get_d[id]' and pid not in ($inserted_pid)"))){
						if(!mysql_query($sql3="delete from $db->package_detail where pkid='$get_d[id]' and pid not in ($inserted_pid)")){
							for($i=0;$i<$t;$i++){
								$prodt=mysql_fetch_assoc($rd);
								$old_pid.=($old_pid? ", " : "").$prodt["pid"];
							}
							$del_errmsg="<br />\n".__("Product ID").__(":")." $old_pid<br />\n<br />\n".__("SQL:")." $sql3<br />\n".__("Error:")." ".mysql_error()."<br />\n";
							$del_errlog="\nProduct ID: $old_pid\n\nSQL: $sql3\nError: ".mysql_error()."\n";
						}
					}
				}

				//product image upload
				$this_prod_root=PROD_ROOT."/".$get_s["id"];
				if($prod_image_uploaded){
					//create image directory
					if(!create_folder_if_not_exist($this_prod_root)){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/orig")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/orig"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/big")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/big"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/medium")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/medium"))."<br />\n";
					}elseif(!create_folder_if_not_exist($this_prod_root."/thumb")){
						$f_errmsg=replace_tag(__("Error storing the uploaded product image file, error creating folder <%dir%>."), array("<%dir%>"=>$this_prod_root."/thumb"))."<br />\n";
					}

					//move & resize image
					if(!$f_errmsg){
						$orig_image=$this_prod_root."/orig/".$prod_image["formatted_name"];
						if(!@move_uploaded_file($prod_image["tmp_name"], $orig_image)){
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/orig/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/big/".$prod_image["formatted_name"], $vars["prod_image_dimension_big"], $vars["prod_image_dimension_big"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/big/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/medium/".$prod_image["formatted_name"], $vars["prod_image_dimension_medium"], $vars["prod_image_dimension_medium"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/medium/"))."<br />\n";
						}elseif(!image_copy_resize($orig_image, $this_prod_root."/thumb/".$prod_image["formatted_name"], $vars["prod_image_dimension_thumb"], $vars["prod_image_dimension_thumb"])) {
							$f_errmsg.=replace_tag(__("Error storing the uploaded product image file, error storing to <%dir%>."), array("<%dir%>"=>$this_prod_root."/thumb/"))."<br />\n";
						}
					}
				}

				//delete old images, if exist / requested
				if(($prod_image_uploaded || $post_s["delete_prod_image"]) && $r_prod["image_file"]){
					if(file_exists($epfo=$this_prod_root."/orig/".$r_prod["image_file"]) && !@unlink($epfo)){
						$epf_fail.=$epfo."<br />\n";
					}
					if(file_exists($epfb=$this_prod_root."/big/".$r_prod["image_file"]) && !@unlink($epfb)){
						$epf_fail.=$epfb."<br />\n";
					}
					if(file_exists($epfm=$this_prod_root."/medium/".$r_prod["image_file"]) && !@unlink($epfm)){
						$epf_fail.=$epfm."<br />\n";
					}
					if(file_exists($epft=$this_prod_root."/thumb/".$r_prod["image_file"]) && !@unlink($epft)){
						$epf_fail.=$epft."<br />\n";
					}
					if($epf_fail){
						$f_errmsg.=__("Error removing the product old image file(s), please manually remove the file(s) below:")."<br />\n<br />\n$epf_fail";
					}
				}

				$msg=__("The product record has been successfully updated.")."<br />\n";
				$logstr="The product record has been successfully updated.";
				$excluded_fields = array('id','cdate');
				$log_arr = mysql_fetch_assoc(mysql_query("select * from $db->products where id='$r_prod[id]'"));
				if($log_arr){
					foreach($log_arr as $f => $v){
						if($f == 'qty'){
							if($r_prod['prod_type'] == 'n' && $post_s['qty_type'] == 'l'){
								$log_fields .= "Quantity = ".($post_s['qty_trans'] == 'c'? '+' : '-').$qty."\n";
							}
						}elseif(!in_array($f, $excluded_fields)){
							$dbr = explode('#', $vars['dbr']['products'][$f]);
							$log_fields .= $dbr[4]." = ".$v."\n";
						}
					}
					$log_fields = rtrim($log_fields, "\n");
				}
				$logstr .= "\n".$log_fields;
				if($qty_errmsg || $jsd_errmsg || $del_errmsg || $f_errmsg){
					$msg.="<br />\n<span class='red'>".__("However, some error(s) had occurred:")."<br />\n".
					($qty_errmsg? __("Quantity for some of the product(s) could not be properly recorded, as below:")."<br />\n$qty_errmsg<br />\n" : "").
					($jsd_errmsg? __("Some of the product(s) could not be properly linked, as below:")."<br />\n$jsd_errmsg<br />\n" : "").
					($del_errmsg? __("Some of the product(s) could not be unlinked, as below:")."<br />\n$del_errmsg<br />\n" : "").
					($f_errmsg? __("There is some error with the product image upload:")."<br />\n$f_errmsg" : "")."</span>";
					$critical_error=$msg;
				}
				if($qty_errlog || $jsd_errlog || $del_errlog){
					$critical_error=$logstr."\nHowever, some error(s) had occurred:\n".
					($qty_errlog? "Quantity for some of the product(s) could not be properly recorded, as below:\n$qty_errlog\n" : "").
					($jsd_errlog? "Some of the product(s) could not be properly linked, as below:\n$jsd_errlog\n" : "").
					($del_errlog? "Some of the product(s) could not be unlinked, as below:\n$del_errlog\n" : "");
					$logstr='';
				}
				$r_prod=mysql_fetch_assoc(mysql_query("select * from $db->products where id='$get_d[id]'"));
			}
		}
	}

	//log critical error
	if($critical_error || $logstr){
		$log_code=$_GET["type"]=="add"? "a-pa" : "a-pe";
		$affected_uid=0;
		$extra_fields = array('pid'=>$get_s['type'] == 'add'? $new_pid : $r_prod['id']);
		if($critical_error){
			//log_activity('e', 'a', $aid, 'n', $affected_uid, $log_code, $critical_error, $extra_fields);
		}elseif($logstr){
			$log_descr = $logstr;
			//log_activity('a', 'a', $aid, 'n', $affected_uid, $log_code, $log_descr, $extra_fields);
		}
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err("There is some error(s), please correct them before continuing:<br />\n<br />\n$errmsg") : "";
}
//#####END PRODUCT POST#####

$form_fields=array("catid"=>"","_refno"=>"","_title"=>"","prod_type"=>"n","_bv"=>0,"_dp"=>0,"_rp"=>0,"qty_type"=>"l","status"=>"active","_remark"=>"","_descr"=>"");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=(!$post_s["__req"]? ($_GET["type"]=="edit"? nhtmlentities($r_prod[$db_fieldname]) : $default) : $post_h[$field]);
}
$fixed_dis=array("_bv","_dp","_rp");
foreach($fixed_dis as $field){
	$ffield=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$ffield."_fix"]=(!$post_s["__req"]? ($_GET["type"]=="edit" && $r_prod["prod_type"]=="p" && $r_prod[$ffield."_fix"]=="y"? true : false) : $post_s[$ffield."_fix"]);
	$dis["_total_".$ffield]=(!$post_s["__req"]? ($_GET["type"]=="edit" && $r_prod["prod_type"]=="p" && $r_prod[$ffield."_fix"]=="y"? $r_prod[$ffield] : "") : $post_s["_total_".$ffield]);
}
$dis["_qty"]=(!$post_s["__req"]? ($_GET["type"]=="edit" && $r_prod["qty_type"]=='l'? $r_prod["qty"] : "") : $post_s["_qty"]);
$dis["add_qty"]=!$post_s["__req"]? 0 : $post_s["add_qty"];

$prodtype_select=$get_s['type'] == 'add'? build_select($r_prodtype, $r_prodtype_d, $dis["prod_type"], "prod_type", $inputbox_style) : "<input type='hidden' name='prod_type' value=\"$dis[prod_type]\" /><input type='text' name='prod_typed' value=\"".$r_prodtype_d[$r_prod['prod_type']]."\" readonly='readonly' $inputbox_style />";
$status_select=build_select($r_status, $r_status_d, $dis["status"], "status", $inputbox_style);
$catid_select=build_select($r_cat, $r_cat_d, $dis["catid"], "catid", $inputbox_style);
$qty_trans_select=build_select($r_qty_trans, $r_qty_trans_d, 'c', "qty_trans");

//get the product items from post / 1st time edit a package
if($_GET["type"]=="edit" && $r_prod["prod_type"]=="p" && !$post_s["__req"]){
	$t=@mysql_num_rows($r=mysql_query("select j.qty, p.refno from $db->package_detail j, $db->products p where j.pkid='$get_d[id]' and j.pid=p.id"));
	for($i=0;$i<$t;$i++){
		$e_prods[$i]=mysql_fetch_assoc($r);
	}
}elseif($post_s["prod_type"]=="p"){
	$i=0;
	foreach($post_s as $f=>$v){
		if(preg_match('/^e_refno_/', $f)){
			$pi=preg_replace('/e_refno_/', '', $f);
			$e_prods[$i]["refno"]=$v;
			$e_prods[$i]["qty"]=$post_d["e_qty_$pi"];
			$i++;
		}
	}
}
unset($prod_list);
for($i=0,$t=count($e_prods);$i<$t;$i++){
	$prod_list.="
	<tr class='ppl_body' id='refno_row_$i'>
		<td><a href='#' name='del_prod' rel='$i'><img src='".M_URL."/images/icons/delete.png' /></a></td>
		<td><input type='text' name='e_refno_$i' value=\"{$e_prods[$i]['refno']}\" style='width:100%;' /></td>
		<td><input type='text' name='e_qty_$i' id=\"pq_input_$i\" value=\"{$e_prods[$i]['qty']}\" style='width:100%;' /></td>
	</tr>";
	$added_refno_js.="
	added_refno[$i] = '".addslashes($e_prods[$i]['refno'])."';";
}
$next_prod_entry_index=$i;

//javascript
ob_start();
?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.livequery.js,fn/fn_in_array.js,fn/fn_array_flip.js"); ?>"></script>
<script type="text/javascript">
var prod_index = <?php echo $next_prod_entry_index; ?>;
jQuery(document).ready(function(j){
	update_package(true);
	j('form[@name=prod_form]').submit(function(){
		j('input[@name=submit_btn]').attr('disabled','disabled');
	});

	<?php #package activate/deactivate ?>
	j('select[@name=prod_type]').click(function(){
		update_package();
	});
	j('select[@name=prod_type]').keyup(function(){
		update_package();
	});

	<?php #bv fixed update ?>
	j('input[@name=bv_fix],input[@name=dp_fix],input[@name=rp_fix]').click(function(){
		var point=j(this).attr('name').replace(/_fix/, '');
		j('input[@name=_total_'+point+']').attr('disabled', j(this).attr('checked')? '' : 'disabled');
		if(j(this).attr('checked')){
			j('input[@name=_total_'+point+']').focus();
		}
	});

	<?php #functions ?>
	function update_package(no_animate){
		if(j('select[@name=prod_type] > option:selected').val() == 'p' || j('input[@name=prod_type]').val() == 'p'){
			if(no_animate){
				j('div#package_prod').show();
				j('div#normal_prod').hide();
			}else{
				j('div#package_prod').slideDown();
				j('div#normal_prod').slideUp();
			}
		}else{
			if(no_animate){
				j('div#package_prod').hide();
				j('div#normal_prod').show();
			}else{
				j('div#package_prod').slideUp();
				j('div#normal_prod').slideDown();
			}
		}
	}
	
	<?php #add new product ?>
	var added_refno = new Array();
	<?php echo $added_refno_js; ?>
	j('a[@name=add_prod]').livequery('click', function(){
		var refno = j(this).attr('rel');
		if(in_array(refno, added_refno)){
			refarr = array_flip(added_refno);
			refi = refarr[refno];
			j('input#pq_input_'+refi).val(parseInt(j('input#pq_input_'+refi).val()) + 1);
		}else{
			j('table#pprod-list').append('<tr class="ppl_body" id="refno_row_'+prod_index+'"><td><a href="#" name="del_prod" rel="'+prod_index+'"><img src="<?php echo M_URL."/images/icons/delete.png"; ?>" /></a></td><td><input type="text" name="e_refno_'+prod_index+'" value="'+refno+'" style="width:100%;" /></td><td><input type="text" name="e_qty_'+prod_index+'" id="pq_input_'+prod_index+'" value="1" style="width:100%;" /></td></tr>');
			added_refno[prod_index] = refno;
			prod_index++;
		}
		return false;
	});
	
	<?php #delete a product ?>
	j('a[@name=del_prod]').livequery('click', function(){
		var refi = j(this).attr('rel');
		j('tr#refno_row_'+refi).remove();
		added_refno[refi] = '';
		return false;
	});
	
	<?php #page nav ?>
	j('p#pml_pagelinks > a').livequery('click', function(){
		var page = j(this).text();
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, page);
		return false;
	});
	
	j('input[@name=btn_prod_search]').click(function(){
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, 1);
	});
	
	function prod_search(catid, title, page){
		j('div#prod_search_div').html('<?php echo addslashes(__("Searching"))."..."; ?>').removeClass('red');
		j.ajax({
			url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&search_prod=1"; ?>',
			data: {'catid': catid, 'title': title, 'page': page},
			type: 'post',
			dataType: 'html',
			error: function(){
				j('div#prod_search_div').html('<?php echo AddSlashes(__("Error searching...")); ?>').addClass('red');
			},
			success: function(data){
				var mesg='';
				var status='';
				if(j('loggedout', data).text()=='loggedout'){
					mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					status=2;
				}else{
					mesg=data;
				}
				j('div#prod_search_div').html(mesg).addClass(status==2? 'red' : '');
			},
			complete: function(){
			}
		});
	}
});
</script>
<?php
$jvscript = ob_get_clean();

//back button
$url_referer=$_SERVER["HTTP_REFERER"];
if($post_s["back_url"]){
	$back_url=$post_s["back_url"];
}elseif($url_referer && !strstr($url_referer, $this_file)){
	$back_url=$url_referer;
}else{
	$back_url=$prod_list_file;
}

//format input row
$display_fields=array("_refno","_title","_bv","_dp","_rp","_remark","_descr");
foreach($form_fields as $field => $default){
	if(in_array($field, $display_fields)){
		$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
		$dbr=explode("#", $vars["dbr"]["products"][$db_fieldname]);
		$readonly=$textarea=false;
		if(in_array($field, array("_remark","_descr"))){
			$textarea=true;
		}
		if($_GET["type"]=="edit" && $field=="_refno"){
			$readonly=true;
		}
		$readonly_str=$readonly? "readonly='readonly'" : "";
		$form_inputfield[$db_fieldname]="
		<tr id='".$db_fieldname."_inputrow'>
			<td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
			<td>".($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
			<input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
		</tr>";
	}
}

//other fix row
$fixed_fields=array("_bv","_dp","_rp");
foreach($fixed_fields as $field){
	$ffield=substr($field, 1);
	$dbr=explode("#", $vars["dbr"]["products"][$ffield]);
	$others_fix_row.="
	<tr id='other_fix_inputrow_".$ffield."'>
		<td width='$td_width'>".replace_tag(__("<%title%> Fixed"), array("<%title%>"=>__($dbr[4]))).__(":")." ".__("*")."</td>
		<td><input type='checkbox' name='".$ffield."_fix' ".($dis[$ffield."_fix"]? "checked='checked'" : "")." id='".$ffield."_fix' /> <label for='".$ffield."_fix'>".replace_tag(__("This package has a fixed <%title%>."), array("<%title%>"=>__($dbr[4])))."</label><br />
		".replace_tag(__("Total <%title%>"), array("<%title%>"=>__($dbr[4]))).__(":")." <input type='text' name='_total_".$ffield."' value=\"".$dis["_total_".$ffield]."\" ".(!$dis[$ffield."_fix"]? "disabled='disabled'" : "")." class='inputbox' />
		</td>
	</tr>";
}
//product search
$o_searchcat = new SearchCat($category_id = 0, $product_title = '', $cur_page = 0, $item_per_page = 10);
$prod_search = $o_searchcat->display();

//product entry row
$cat_select = build_select($r_scat, $r_scat_d, '', 'category_id', "style='width:100%;'");
$prod_entry_row="
	<tr id='prod_entry_inputrow'>
		<td width='$td_width'>".__("Link with Products").__(":")." ".__("*")."</td>
		<td>".__("Existing Products").":<br />
			<table class='prod-mini-list'>
				<tr class='pml_body'>
					<td>".__("Category").":</td>
					<td><div id='div_category_search'>$cat_select</div></td>
				</tr>
				<tr class='pml_body'>
					<td>".__("Search").":</td>
					<td><input type='text' name='prod_search' value='' style='width:100%;' /></td>
				</tr>
				<tr class='pml_body'>
					<td colspan='2' class='center'><input type='button' name='btn_prod_search' value='".__("Search")."' /></td>
				</tr>
			</table><br />
			<div id='prod_search_div'>$prod_search</div>
			<p>".__("Below is the list of product for this package. To add a product to this package, browse from the product list above and click to add.")."</p>
			<table class='package-prod-list' id='pprod-list'>
				<tr class='ppl_header'>
					<td></td>
					<td>".__("Reference No.")."</td>
					<td>".__("Quantity")."</td>
				</tr>
				$prod_list
			</table>
		</td>
	</tr>";
//quantity row
$qty_row="
	<tr id='qty_inputrow'>
		<td width='$td_width'>".__("Quantity").__(":")." ".__("*")."</td>
		<td>".($get_s['type'] == 'edit'? __("Current quantity").": ".($r_prod['qty_type']=='u'? __("Unlimited") : $r_prod['qty'])."<br />" : '')."<input type='radio' name='qty_type' value='u' ".($dis["qty_type"]=="u"? "checked='checked'" : "")." id='qty_unl' /> <label for='qty_unl'>".__("Unlimited")."</label><br />\n
		<input type='radio' name='qty_type' value='l' ".($dis["qty_type"]=="l"? "checked='checked'" : "")." id='qty_lim' /> <label for='qty_lim'>".($get_s['type'] == 'add' ? __("Limited, initial quantity") : __("Limited, add/deduct quantity")).__(":")."</label> ".($get_s['type'] == 'edit'? $qty_trans_select.' ' : '')."<input type='text' name='_qty' class='inputbox' ".($get_s['type'] == 'add'? "value=\"$dis[_qty]\"" : '')." /></td>
	</tr>";
//image upload
if($_GET["type"]=="edit" && $r_prod["image_file"]){
	$existing_prod_img="<img src='".PROD_URL."/".$get_s["id"]."/big/".$r_prod["image_file"]."' /><br />\n<input type='checkbox' name='delete_prod_image' id='del_pef' /> <label for='del_pef'>".__("Delete the above image")."</label> <a href='".PROD_URL."/".$get_s["id"]."/orig/".$r_prod["image_file"]."' target='_blank'>".$r_prod["image_file"]."</a><br />\n<br />\n";
}
$image_upload_row="
	<tr>
		<td width='$td_width'>".__("Product Image").__(":")."</td>
		<td>$existing_prod_img<input type='file' name='prod_image' size='60' /><br />\n
		".replace_tag(__("Accepts only <%format%>."), array("<%format%>"=>implode(" / ", $vars["accepted_image_format"])))." ".
		replace_tag(__("Maximum upload size is <%x%> <%unit%>."), array("<%x%>"=>strval($vars["prod_image_max_size"]), "<%unit%>"=>__("KB")))." ".
		replace_tag(__("Recommended image dimension is <%width%> x <%height%>."), array("<%width%>"=>strval($vars["prod_image_dimension_big"]), "<%height%>"=>strval($vars["prod_image_dimension_big"])))."</td>
	</tr>";

$manage_product=($errmsg || $msg?
"$errmsg $msg" : "")."
<form name='prod_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]' enctype='multipart/form-data'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='back_url' value=\"$back_url\" />
<table class='amt_table'>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='button' value='Back' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
		<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Product") : __("Add Product"))."\" />
		</td>
	</tr>
	<tr class='amt_header'>
		<td colspan='2'>".__("Product Information")."</td>
	</tr>".($_GET["type"]=="edit"? "
	<tr>
		<td width='$td_width'>".__("Product ID").__(":")."</td>
		<td>$get_h[id]</td>
	</tr>" : "")."
	<tr>
		<td>".__("Category").__(":")." ".__("*")."</td>
		<td><div id='div_category'>$catid_select</div></td>
	</tr>
	$form_inputfield[title]
	$form_inputfield[refno]
	<tr>
		<td>".__("Product Type").__(":")." ".__("*")."</td>
		<td>$prodtype_select<br />\n".__("A package can link with multiple items and have their respective quantity.")."</td>
	</tr>
</table>
<div id='package_prod'>
<table class='amt_table'>
	$prod_entry_row
	$others_fix_row
</table>
</div>
<div id='normal_prod'>
<table class='amt_table'>
	$form_inputfield[bv]
	$form_inputfield[dp]
	$form_inputfield[rp]
	$qty_row
</table>
</div>
<table class='amt_table'>
	$image_upload_row
	$form_inputfield[descr]
	$form_inputfield[remark]
	<tr>
		<td>".__("Status").__(":")." ".__("*")."</td>
		<td>$status_select</td>
	</tr>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='button' value='Back' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
		<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Product") : __("Add Product"))."\" />
		</td>
	</tr>
</table>
</form>";

$content="<h2>$page_title</h2>$manage_product";

print format_admin_page($content, $this_title, $jvscript);
?>